package by.semerikov.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import by.semerikov.converter.UserSessionConverter;
import by.semerikov.dao.DAOFactory;
import by.semerikov.dao.IUserSessionDAO;
import by.semerikov.data.Connector;
import by.semerikov.entity.UserSessionEntity;
import by.semerikov.exceptions.ConnectorException;
import by.semerikov.exceptions.DAOException;
import by.semerikov.model.UserSession;

public class UserSessionService {
	UserSessionConverter userSessionConverter = new UserSessionConverter();
	

	public void createUserSession(UserSession object) throws DAOException, ConnectorException
	{
		try {
			Connection conn = Connector.getConnection();
			conn.setAutoCommit(false);
			IUserSessionDAO usd = DAOFactory.getInstance().getUserSessionDAO();
			usd.setConnection(conn);
			usd.create(userSessionConverter.convertToEntity(object));
			conn.setAutoCommit(true);
			conn.close();
		} catch (SQLException e) {
			throw new ConnectorException("exception.service.usersession.create",e);
		}
	}
	
	public List<UserSession> readUserSession(UserSession object) throws DAOException, ConnectorException
	{
		List<UserSession> result = new ArrayList<UserSession>();
		List<UserSessionEntity> resultEntity = new ArrayList<UserSessionEntity>();
		try {
			
			Connection conn = Connector.getConnection();
			conn.setAutoCommit(false);
			IUserSessionDAO usd =  DAOFactory.getInstance().getUserSessionDAO();
			usd.setConnection(conn);
			resultEntity = usd.read(userSessionConverter.convertToEntity(object));
			conn.setAutoCommit(true);
			conn.close();
			for (int i = 0; i < resultEntity.size(); i++) {
				result.add(userSessionConverter.convertToModel(resultEntity.get(i)));
			}
		} catch (SQLException e) {
			throw new ConnectorException("exception.service.usersession.read",e);
		}
		return result;
	}
	
	public void deleteUserSession(UserSession object) throws DAOException, ConnectorException
	{
		try {
			Connection conn = Connector.getConnection();
			conn.setAutoCommit(false);
			IUserSessionDAO usd =  DAOFactory.getInstance().getUserSessionDAO();
			usd.setConnection(conn);
			usd.delete(userSessionConverter.convertToEntity(object));
			conn.setAutoCommit(true);
			conn.close();
		} catch (SQLException e) {
			throw new ConnectorException("exception.service.usersession.delete",e);
		}
	}
}
